package com.tan.utils;

import com.tan.pojo.Menu;
import io.swagger.annotations.Api;

import java.util.ArrayList;
import java.util.List;

/**
 * 封装一个类 用户创建树状菜单
 */
public class BuildMenuTreeUtil {

    // 得到一级菜单
    public static List<Menu> buildMenuTree(List<Menu> menuList) {

        final ArrayList<Menu> menus = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentId() == 0) {
                menus.add(menu);
            }
        }

        for (Menu menu : menus) {
            menu.setChildMenus(getChild(menu.getId(), menuList));
        }

        menus.sort((o1, o2) -> {
            if (o1.getOrderNum() > o2.getOrderNum()) {
                return 1;
            } else if (o1.getOrderNum() < o2.getOrderNum()) {
                return -1;
            }
            return 0;
        });

        return menus;
    }

    // 遍历一级菜单下的子菜单
    private static List<Menu> getChild(Long id, List<Menu> menuList) {

        final ArrayList<Menu> childrenMenus = new ArrayList<>();

        for (Menu menu : menuList) {
            if (menu.getParentId().equals(id)){
                childrenMenus.add(menu);
            }
        }

        childrenMenus.sort((o1, o2) -> {
            if (o1.getOrderNum() > o2.getOrderNum()) {
                return 1;
            } else if (o1.getOrderNum() < o2.getOrderNum()) {
                return -1;
            }
            return 0;
        });

        // 递归调用自己的方法 得到全部的子菜单 添加到自己的子菜单集合中
        for (Menu childrenMenu : childrenMenus) {
            childrenMenu.setChildMenus(getChild(childrenMenu.getId(), menuList));
        }

        return childrenMenus;
    }
}
